package it.unical.mat.aec.processTests;

import it.unical.mat.aec.model.Domanda;
import it.unical.mat.aec.model.Studente;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class LettoreXMLFileTest implements LettoreFileTest {
	
	private File currentFile;
	private DocumentBuilderFactory builderFactory;
	private DocumentBuilder documentBuilder;
	private Document document;
	
	public LettoreXMLFileTest() throws LettoreFileTestException {
		builderFactory=DocumentBuilderFactory.newInstance();
		try {
			documentBuilder=builderFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new LettoreFileTestException(e.getLocalizedMessage());
		}
	}

	@Override
	public int getIdTest(File file) throws LettoreFileTestException{
		Integer id=null;
		try {
			inizializzaDocumento(file);
			NodeList nodes=document.getElementsByTagName("test");
			Node node=nodes.item(0);
			NamedNodeMap attributes=node.getAttributes();
			Node nodeId=attributes.getNamedItem("id");
			id=Integer.parseInt(nodeId.getNodeValue());
		} catch (Exception e) {}
		if(id==null)
			throw new LettoreFileTestException("Can't read idTest of file "+file.getName());
		return id;
	}


	@Override
	public int getIdTraccia(File file) throws LettoreFileTestException {
		Integer idTraccia=null;
		try {
			inizializzaDocumento(file);
			NodeList nodes=document.getElementsByTagName("test");
			Node node=nodes.item(0);
			NamedNodeMap attributes=node.getAttributes();
			Node nodeId=attributes.getNamedItem("idTraccia");
			idTraccia=Integer.parseInt(nodeId.getNodeValue());
		} catch (Exception e) {}
		if(idTraccia==null)
			throw new LettoreFileTestException("Can't read idTraccia of file "+file.getName());
		return idTraccia;
	}

	@Override
	public Studente getStudente(File file) throws LettoreFileTestException {
		Studente studente=null;
		try {
			inizializzaDocumento(file);
			NodeList nodes=document.getElementsByTagName("test");
			Node node=nodes.item(0);
			NodeList childNode=node.getChildNodes();
			for(int i=0;i<childNode.getLength();i++)
				if(childNode.item(i).getNodeName().equalsIgnoreCase("studente")){
					Node student=childNode.item(i);
					String matricola = null,nome = null,cognome = null;
					for(int j=0;j<student.getChildNodes().getLength();j++){
						String buffer=student.getChildNodes().item(j).getTextContent();
						if(student.getChildNodes().item(j).getNodeName().equals("matricola"))
							matricola=buffer;
						else if(student.getChildNodes().item(j).getNodeName().equals("nome"))
							nome=buffer;
						else if(student.getChildNodes().item(j).getNodeName().equals("cognome"))
							cognome=buffer;
					}
					if(matricola!=null){
						studente=new Studente(Integer.parseInt(matricola));
						if(nome!=null)
							studente.setNome(nome);
						if(cognome!=null)
							studente.setCognome(cognome);
					}
					break;
				}
		} catch (Exception e) {}
		if(studente==null)
			throw new LettoreFileTestException("Can't read student of file "+file.getName());
		return studente;
	}

	@Override
	public ArrayList<Domanda> getDomande(File file) throws LettoreFileTestException {
		ArrayList<Domanda> domande=new ArrayList<Domanda>();
		int erroreDomande=0;
		try {
			inizializzaDocumento(file);
			NodeList nodes=document.getElementsByTagName("test");
			Node node=nodes.item(0);
			NodeList childNode=node.getChildNodes();
			for(int i=0;i<childNode.getLength();i++)
				if(childNode.item(i).getNodeName().equalsIgnoreCase("domande")){
					NodeList domandeNode=childNode.item(i).getChildNodes();
					for(int j=0;j<domandeNode.getLength();j++)
						if(domandeNode.item(j).getNodeName().equalsIgnoreCase("domanda")){
							Domanda domanda=estraiDomanda(domandeNode.item(j));
							if(domanda==null)
								erroreDomande++;
							else
								domande.add(domanda);
						}
				}
		} catch (Exception e) {}
		if(erroreDomande>0)
			throw new LettoreFileTestException("Can't read "+erroreDomande+" quest of file "+file.getName());
		return domande;
	}

	private Domanda estraiDomanda(Node node) {
		Domanda domanda=null;
		NamedNodeMap attributes=node.getAttributes();
		Node nodeId=attributes.getNamedItem("id");
		Integer idDomanda=null;
		try{
			idDomanda=Integer.parseInt(nodeId.getNodeValue());
		}catch (Exception e) {}
		String testoDomanda = null,risposta = null;
		for(int j=0;j<node.getChildNodes().getLength();j++){
			String buffer=node.getChildNodes().item(j).getTextContent();
			if(node.getChildNodes().item(j).getNodeName().equals("testo"))
				testoDomanda=buffer;
			else if(node.getChildNodes().item(j).getNodeName().equals("risposta"))
				risposta=buffer;
		}
		if(idDomanda!=null && testoDomanda!=null && risposta!=null)
			domanda=new Domanda(idDomanda, testoDomanda, risposta, 0);
		return domanda;
	}

	private void inizializzaDocumento(File file) throws SAXException,IOException {
		if(currentFile==null || currentFile!=file){
			document=documentBuilder.parse(file);
			currentFile=file;
		}
		document.getDocumentElement().normalize();
	}

	@Override
	public boolean isValidFile(File file) {
		if(file.getName().endsWith(".xml"))
			return true;
		return false;
	}
}
